package com.yunti.yntk.service;

import android.content.Context;
import android.content.res.AssetManager;

import com.alibaba.fastjson.JSONObject;
import com.koushikdutta.async.callback.CompletedCallback;
import com.koushikdutta.async.http.server.AsyncHttpServer;
import com.koushikdutta.async.http.server.AsyncHttpServerRequest;
import com.koushikdutta.async.http.server.AsyncHttpServerResponse;
import com.koushikdutta.async.http.server.HttpServerRequestCallback;
import com.koushikdutta.async.http.WebSocket;
import com.yunti.yntk.model.FieldShowRes;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

public class WebServer {

    private final AssetManager assetManager;

    private AsyncHttpServer server;
    private int port;
    private Context context;

    HashMap<String,WebSocket> webSocketHashMap = new HashMap<>();

    public WebServer(AssetManager assetManager, Context context, int port) {
        this.assetManager = assetManager;
        this.context = context;
        this.port = port;
        this.server = new AsyncHttpServer();
    }

    private String getMimeType(String uri) {
        if (uri.endsWith(".html")) return "text/html";
        if (uri.endsWith(".js")) return "application/javascript";
        if (uri.endsWith(".css")) return "text/css";
        if (uri.endsWith(".png")) return "image/png";
        if (uri.endsWith(".jpg") || uri.endsWith(".jpeg")) return "image/jpeg";
        return "text/plain";
    }

    public void start() {
        // 处理HTTP请求，返回asset下的index.html
        server.get("/www/.*", new HttpServerRequestCallback() {
            @Override
            public void onRequest(AsyncHttpServerRequest request, AsyncHttpServerResponse response) {
                // 排除 WebSocket 路径
                try {
                    String uri = request.getUrl();
                    uri = uri.split("\\?")[0];
                    uri = uri.replaceAll("/www","");
                    // 从assets/www目录读取文件
                    InputStream inputStream = assetManager.open("www" + uri);
                    byte[] buffer = new byte[inputStream.available()];
                    inputStream.read(buffer);
                    inputStream.close();
                    String mimeType = getMimeType("www" + uri);
                    response.send(mimeType, buffer);
                } catch (IOException e) {
                    response.code(404).send("Not Found");
                }

            }
        });


        // 处理WebSocket连接
        server.websocket("/ws", new AsyncHttpServer.WebSocketRequestCallback() {
            @Override
            public void onConnected(final WebSocket webSocket, AsyncHttpServerRequest request) {
                String url = request.getUrl();
                String id = "";

                java.util.regex.Pattern pattern = java.util.regex.Pattern.compile("[?&]id=([^&]*)");
                java.util.regex.Matcher matcher = pattern.matcher(url);

                if (matcher.find()) {
                    id = matcher.group(1);
                }
                System.out.println(id+"，连接上来");
                webSocketHashMap.put(id,webSocket);
                webSocket.setStringCallback(new WebSocket.StringCallback() {
                    @Override
                    public void onStringAvailable(String s) {
                        // 处理收到的WebSocket消息
                        webSocket.send("Echo: " + s);

                    }
                });
                String finalId = id;
                webSocket.setClosedCallback(new CompletedCallback() {
                    @Override
                    public void onCompleted(Exception ex) {
                        webSocketHashMap.remove(finalId);
                    }
                });


            }


        });

        // 启动服务器
        server.listen(port);
    }

    public void sendLedInfo(FieldShowRes fieldShowRes){
        // 遍历键值对
        for (Map.Entry<String, WebSocket> entry : webSocketHashMap.entrySet()) {
            String key = entry.getKey();
            WebSocket webSocket = entry.getValue();
            sendLedInfo(webSocket,fieldShowRes);
        }
    }

    public void sendLedInfo(WebSocket webSocket,FieldShowRes fieldShowRes){
        webSocket.send(JSONObject.toJSONString(fieldShowRes));
    }

    public void stop() {
        server.stop();
    }
}